﻿using System;
using System.Collections.Generic;
using ZhCun.DbCore;
using ZhCun.DbCore.Cores;
using ZhCun.DbCore.Entitys;
using ZhCun.Utils;
using ZhCun.Utils.Helpers;
using ZhCun.WebCommon.DBModels;

namespace ZhCun.WebCommon.AL
{
    public class BaseAL
    {
        /// <summary>
        /// 用户操作的连接字符串
        /// </summary>
        protected static string DBUserConnString
        {
            get
            {
                return ConfigHelper.GetConnectString(Constants.DB_USER);
            }
        }
        /// <summary>
        /// 日志操作的连接字符串
        /// </summary>
        protected static string DBLogConnString
        {
            get { return ConfigHelper.GetConnectString(Constants.DB_LOG); }
        }

        /// <summary>
        /// 默认不创建 DBContext 子类从构造函数再创建
        /// </summary>
        public BaseAL()
        {
            _DB = CreateDBContext(DBUserConnString);
        }
        /// <summary>
        /// 根据连接字符串创建 DBContext 对象
        /// </summary>
        public BaseAL(string connStr)
        {
            _DB = CreateDBContext(connStr);
        }
        /// <summary>
        /// 创建数据库上下文
        /// </summary>
        protected BaseDBContext CreateDBContext(string connStr)
        {
            string dbTypeString = AppCommonConfig.AppSettings.DBType;
            EmDbType dbType;
            //SQLServer = 1,SQLite = 2,Oracle = 3,MySQL = 4,OleDb = 5
            switch (dbTypeString)
            {
                case "SQLServer":
                    dbType = EmDbType.SQLServer;
                    break;
                case "SQLite":
                    dbType = EmDbType.SQLite;
                    break;
                case "Oracle":
                    dbType = EmDbType.Oracle;
                    break;
                case "MySQL":
                    dbType = EmDbType.MySQL;
                    break;
                default:
                    throw new Exception("数据库类型设置错误");
            }
            return new BaseDBContext(dbType, connStr);
        }

        protected BaseDBContext _DB;

        public DBContext DB { get { return _DB; } }

        public string LoginHost { get { return _DB.LoginHost; } }

        /// <summary>
        /// 设置当前登录用户
        /// </summary>
        public virtual void SetLoginState(TSysLoginToken loginState, bool useDataRights = true)
        {
            _DB.SetLoginUser(loginState, useDataRights);
        }

        public void SetLoginHost(string loginHost)
        {
            _DB.SetLoginHost(loginHost);
        }

        /// <summary>
        /// 当前登录用户对象
        /// </summary>
        public TSysLoginToken LoginUser { get { return _DB.LoginUser; } }

        public virtual DateTime GetNowTime()
        {
            return DateTime.Now;
        }

        public QueryCondition<TEntity> CreateQueryCondition<TEntity>() where TEntity : EntityBase, new()
        {
            return _DB.CreateQuery<TEntity>();
        }

        public virtual List<TEntity> GetPagerList<TEntity>(int pageNo, int pageSize, out int total, Action<QueryCondition<TEntity>> QueryHandle)
            where TEntity : EntityBase, new()
        {
            var query = CreateQueryCondition<TEntity>();
            query.PageNo = pageNo;
            query.PageSize = pageSize;
            QueryHandle(query);
            var rList = DB.Query<TEntity>(query).ToList(true);
            total = query.Total;
            return rList;
        }

        /// <summary>
        /// 写数据库日志
        /// </summary>
        public void WriteLog(string logContent, params object[] args)
        {
            TSysLog log = new TSysLog();
            if (LoginUser != null)
            {
                log.ClientSN = LoginUser.LoginClientSN;
                log.LoginName = LoginUser.LoginName;
                log.UserName = LoginUser.UserName;
                //log.AddHost = LoginUser.LoginHost;
                //log.CreateUserId = LoginUser.LoginUserId;
                log.LogType = 0;
            }
            else
            {
                log.LogType = 1;
            }
            log.LogContent = string.Format(logContent, args);
            DBLog.WriteLog(log);
        }
        /// <summary>
        /// 当前用户是是否是管理员（000）
        /// </summary>
        /// <returns></returns>
        public bool IsManageUser()
        {
            return AppCommonConfig.AppSettings.ManageUserId.Equals(LoginUser?.LoginUserId, StringComparison.CurrentCultureIgnoreCase);
        }
        /// <summary>
        /// 当前登录用户是否是管理员角色
        /// </summary>
        public bool IsManageRole()
        {
            return AppCommonConfig.AppSettings.ManageRoleId.Equals(LoginUser?.RoleId, StringComparison.CurrentCultureIgnoreCase);
        }
    }
}